package com.bdqn.BookManage.servlet;

import com.bdqn.BookManage.biz.BookInfoBiz;
import com.bdqn.BookManage.biz.impl.BookInfoBizImpl;
import com.bdqn.BookManage.po.BookInfo;
import com.bdqn.BookManage.view.BookInfoView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : CP
 * @version: 1.0
 * @program : BookManage
 * @description : 购物车处理器
 * @date : 2020-07-28 12:01
 **/
@WebServlet("/shoppingCart")
public class ShoppingTrolleyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        BookInfoBiz bookInfoBiz = new BookInfoBizImpl();
        
        String id = req.getParameter("id");
        Map<String,BookInfoView> shoppingCart = (Map<String,BookInfoView>) session.getAttribute("cart");
        if(shoppingCart == null){
            /** 生成购物车 */
            shoppingCart = new HashMap<>();
        }

        /** 查看商品是否重复 */
        BookInfoView bookInfoView = shoppingCart.get(id);
        if(bookInfoView==null){
            /** 获取图书信息 */
            BookInfo bookInfo = bookInfoBiz.querBookInfo(Integer.valueOf(id));
            /** 封装一条完整的商品信息 */
            bookInfoView = new BookInfoView(1,bookInfo,1);
        }else{
            /** 商品重复进行加一操作 */
            if(bookInfoView.getAmount()+1>bookInfoView.getBookInfo().getStock()){
                /** 超出库存范围 */
                resp.getWriter().print("<script>alert('商品库存不足!');location.href='shoppingTrolley.jsp';</script>");
            }else{
                /** 加一 */
                bookInfoView.setAmount(bookInfoView.getAmount()+1);
            }
        }

        /** 将数据保存到购物车中 */
        shoppingCart.put(id,bookInfoView);


        /** 将购物车持久化保存 */
        session.setAttribute("cart",shoppingCart);
        /** 将数据保存在客户端 */
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);

        resp.sendRedirect("shoppingTrolley.jsp");
    }
}
